require(xtable)
require(data.table)
## total number of pages
.ntabs <- 14
## mean height in cm for normal draws
## for M and F,
## source wikipedia, US
## taking SD = mean/10...
.means <- c(m=176, f=162)

## get 1/2 m & female w/sample
## randomly select which is which
## for each, get 10 and 20 draws
.sample <- rep(c('m','f'), each=.ntabs %/% 2)
.specs <- list(
    small = list(size =10, sex=sample(.sample, .ntabs)),
    large = list(size=20, sex=sample(.sample, .ntabs))
)


## for each table, make the draws and record everything 
## pages 1-N
tablist <- llply(1:.ntabs, function(.n) {
    ## large table and small table 
    llply(.specs, function(.spec) {
        ret <- within(list(), {
            ntab <- .n
            sex <- .spec$sex[.n]
            .mean <- .means[[sex]]
            nsamples <- .spec$size
            ## nice shaped matrix for xtable 
            ## sd ~ mean
            dat <- matrix(sort(rnorm(nsamples, mean=.mean, sd=.mean/10)), byrow=T, ncol=5)
        })
    })
})

## print all the tables here
.filename <- 'wk7-xtabs.tex'

## convenience function,
## takes the list and prints data as table, along w/id
my.print.xtab <- function(x) {
    .heading = sprintf('\n\\\\centering\nTable %d-%d\n\n', x$ntab, x$nsamples)
    system(sprintf(" echo '%s' >> %s", .heading, .filename))
    print(
        xtable(x$dat, digits=0), 
        file=.filename,
        append=T,
        include.rownames=F,
        include.colnames=F
    )
}

## clear out the .tex file to start
system(sprintf('echo " " > %s', .filename))
## for each page, print small and large tables
l_ply(tablist, function(x){
    my.print.xtab(x$small)
    system(sprintf(" echo '\n' >> %s", .filename))
    my.print.xtab(x$large)
    ## separate each page
    system(sprintf(" echo '\\\\clearpage\n' >> %s", .filename))
})



## get table specifying which is which 
tab.ids = ldply(tablist, function(x) { 
    ldply(c('large', 'small'), function(.size) {
        data.frame(Table=x[[.size]]$ntab, Size=x[[.size]]$nsamples, Sex=x[[.size]]$sex)
    })
})
## use data table to sort
tab.ids <- data.table(tab.ids, key=c('Sex', 'Table', 'Size'))

## print thrice
for(ii in 1:3) {
    print(xtable(tab.ids, digits=0), include.rownames=F, file=.filename, append=T)
    system(sprintf(" echo '\\\\clearpage\n' >> %s", .filename))
}
